package pl.pawluk.inz.security.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import pl.pawluk.inz.security.AuthenticationService;
import pl.pawluk.inz.utils.EncryptionUtils;

import javax.annotation.Resource;

@Service
public class AuthenticationServiceImpl implements AuthenticationService {
    private static final Log log = LogFactory.getLog(AuthenticationServiceImpl.class);

    @Resource(name = "authenticationManager")
    private AuthenticationManager authenticationManager; // specific for Spring Security

    @Override
    public boolean login(String username, String password) {
        log.info("Rozpoczynam autentykację");
        Authentication authenticate = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(
                        username, EncryptionUtils.encode(password)));
        if (authenticate.isAuthenticated()) {
            SecurityContextHolder.getContext().setAuthentication(
                    authenticate);
            log.info("Autentykacja zakończona sukcesem");
            return true;
        }
        log.info("Błąd autentykacji");
        return false;
    }

    @Override
    public String getUserName() {
        return SecurityContextHolder.getContext().getAuthentication().getName();
    }

    @Override
    public void logout() {
        SecurityContextHolder.getContext().setAuthentication(null);
    }


}
